package com.leo.leetcode.s100;

/**
 * https://leetcode.com/problems/add-two-numbers/description/
 * @author xuexiaolei
 * @version 2017年10月27日
 */
public class T02AddTwoNumbers {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);//虚头指针
        ListNode current = head;//当前指针
        boolean isGreaterTen = false;
        while (l1 != null || l2 != null || isGreaterTen){
            int result = 0;
            if (l1 != null){
                result += l1.val;
                l1 = l1.next;
            }
            if (l2 != null){
                result += l2.val;
                l2 = l2.next;
            }
            if (isGreaterTen){
                result++;
            }
            if (result >= 10){
                isGreaterTen = true;
                result = result % 10;
            } else {
                isGreaterTen = false;
            }
            current.next = new ListNode(result);
            current = current.next;
        }
        return head.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        l2.next.next.next = new ListNode(3);
        ListNode result = addTwoNumbers(l1, l2);
        while (result != null){
            System.out.print(result.val);
            result = result.next;
        }
    }
}
